package com.sgb.merchant.view.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.FileEntity;
import com.sgb.link.entity.merchant.InvestmentEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivityCommitPublishBinding;
import com.sgb.merchant.viewmodel.ProjectCommitViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * @author: 王彬臣
 * @date: 2021/8/13
 * @Description: 发布投资项目要求页
 */
@Route(path = PathMerchant.ProjectCommitActivity)
public class ProjectCommitActivity extends BaseActivity<ProjectCommitViewModel, MerchantActivityCommitPublishBinding> {
    @Autowired(name = RouterKey.DATA)
    InvestmentEntity investmentEntity;

    @Autowired(name = RouterKey.DATA1)
    ArrayList<String> urlList;
    @Autowired(name = RouterKey.BOOLEAN,desc="是否来着我的页面")
    boolean isSelf=false;

    List<FileEntity> fileEntities = new ArrayList<>();

    List<InvestmentEntity.ImagesBean> imagesBeans;
    String condition, require, other;
    boolean hasContent;
    private int currentImgNum;
    boolean isPublish;

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_commit_publish;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(ProjectCommitViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        if(TextUtils.isEmpty(investmentEntity.getItemNo())){
            isPublish=true;
        }else{
            isPublish=false;
        }
        mBinding.setClick(this);
        mBinding.includeTitle.titleView.setText("招商项目");
        mBinding.includeTitle.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getContent();
                if (hasContent) {
                    showHintDialog();
                    return;
                }
                finish();
            }
        });
        if(!TextUtils.isEmpty(investmentEntity.getSeniorityInfo())) {
            mBinding.etCondition.setText(investmentEntity.getSeniorityInfo());
        }
        if(!TextUtils.isEmpty(investmentEntity.getCollaboratorQualifications())) {
            mBinding.etRequire.setText(investmentEntity.getCollaboratorQualifications());
        }
        if(!TextUtils.isEmpty(investmentEntity.getOtherRequirement())) {
            mBinding.etOther.setText(investmentEntity.getOtherRequirement());
        }
        if (investmentEntity.getImages() == null) {
            imagesBeans = new ArrayList<>();
        } else {
            imagesBeans = investmentEntity.getImages();
        }
        mViewModel.ldResult.observe(this, isSuccess -> {
            if(isSuccess) {

                //关闭发布投资页面
                EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_FINISH_PUBLIC));
                //刷新详情页
                EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVEN_MERCHANT_SELF_REFRESH_DETAIL));
                if (isPublish) {
                    MToast.showToast(this, "发布成功");
                } else {
                    MToast.showToast(this, "编辑成功");
                }
                if(isSelf){
                    ARouter.getInstance().build(PathMerchant.SelfProjectListActivity).navigation();
                }else{
                    //刷新列表页
                    EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_REFRESH));
                }
                finish();
            }else{

                //刷新详情页
                EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVEN_MERCHANT_SELF_REFRESH_DETAIL));
                new RoundDialog.Builder(this)
                        .title("温馨提示")
                        .content("该数据状态已发生变化，请刷新后再进行操作。")
                        .confirm("知道了")
                        .singleBtn(true)
                        .cancelable(false)
                        .confirmCallback(v->{
                            //刷新列表页
                            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_REFRESH));
                            setResult(RESULT_OK);
                            finish();
                        })
                        .show();
            }
        });
        mViewModel.ldUrl.observe(this, imagesBean -> {
            imagesBeans.get(imagesBean.getPosition()).setImageUrl(imagesBean.getImgUrl());
            if (currentImgNum + 1 <fileEntities.size()) {
                currentImgNum = currentImgNum + 1;
                mViewModel.uploadPic(fileEntities.get(currentImgNum).getFile(), currentImgNum);
            }else{
                DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(true);
                investmentEntity.setImages(imagesBeans);
                mViewModel.publishProject(investmentEntity);
            }
        });
        mViewModel.ldFail.observe(this,data->{
            mBinding.tvCommit.setEnabled(true);
            new RoundDialog.Builder(this)
                    .title("提交失败")
                    .content(!TextUtils.isEmpty(data.getMsg())?data.getMsg():"")
                    .confirm("知道了")
                    .singleBtn(true)
                    .cancelable(false)
                    .show();
        });
        mViewModel.ldState.observe(this,state->{
            if(state){
                if (fileEntities.size() > 0) {
                    DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false);
                    mViewModel.uploadPic(fileEntities.get(0).getFile(), fileEntities.get(0).getPosition());
                } else {
                    DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false);
                    mViewModel.publishProject(investmentEntity);
                }
            }
        });


        //筛选出需要上传的图片并标记位置
        for (int i = 0; i < urlList.size(); i++) {
            String url = urlList.get(i);
            FileEntity fileEntity = new FileEntity();
            InvestmentEntity.ImagesBean imagesBean = new InvestmentEntity.ImagesBean();
            if (!url.contains("http") || !url.contains("https")) {
                fileEntity.setFile(new File(url));
                fileEntity.setPosition(i);
                fileEntities.add(fileEntity);
                imagesBeans.add(imagesBean);
            }else if(imagesBeans.size()==0){
                imagesBeans.add(imagesBean);
            }
        }
    }

    public void getContent() {
        condition = mBinding.etCondition.getText().toString();
        require = mBinding.etRequire.getText().toString();
        other = mBinding.etOther.getText().toString();
        if (!TextUtils.isEmpty(condition) || !TextUtils.isEmpty(require) || !TextUtils.isEmpty(other)) {
            hasContent = true;
        } else {
            hasContent = false;
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_last_page) {
            getContent();
            investmentEntity.setSeniorityInfo(TextUtils.isEmpty(condition) ? "" : condition);
            investmentEntity.setCollaboratorQualifications(TextUtils.isEmpty(require) ? "" : require);
            investmentEntity.setOtherRequirement(TextUtils.isEmpty(other) ? "" : other);
            Intent intent = new Intent();
            intent.putExtra("info", investmentEntity);
            setResult(RESULT_OK, intent);
            finish();

        } else if (v.getId() == R.id.tv_commit) {
            mBinding.tvCommit.setEnabled(false);//禁止点击，接口请求是不才允许点击
            getContent();
            if (TextUtils.isEmpty(condition)) {
                MToast.showToast(this, "请输入合作方资格条件!");
                return;
            }
            if (TextUtils.isEmpty(require)) {
                MToast.showToast(this, "请输入资质要求!");
                return;
            }
            investmentEntity.setSeniorityInfo(condition);
            investmentEntity.setCollaboratorQualifications(require);
            if (!TextUtils.isEmpty(other)) {
                investmentEntity.setOtherRequirement(other);
            }else{
                investmentEntity.setOtherRequirement("");
            }
            if(TextUtils.isEmpty(investmentEntity.getItemNo())) {
                if (fileEntities.size() > 0) {
                    DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false);
                    mViewModel.uploadPic(fileEntities.get(0).getFile(), fileEntities.get(0).getPosition());
                } else {
                    DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false);
                    mViewModel.publishProject(investmentEntity);
                }
            }else{
                mViewModel.getCurrentState(Long.valueOf(investmentEntity.getItemNo()));
            }
        }

    }

    private void showHintDialog() {
        new RoundDialog.Builder(this)
                .title("温馨提示")
                .content("当前操作会丢失已填写的信息，确定是否继续？")
                .cancel("取消")
                .confirm("确定")
                .cancelable(false)
                .confirmCallback(v12 -> finish()).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            getContent();
            if (hasContent) {
                showHintDialog();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
